package com.change.declare.declare.BO;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.change.declare.declare.entity.OrdersEntity;
import com.change.declare.declare.service.OrdersService;
import lombok.Data;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

@Component
@Data
public class TinyOrderIDGenerator {
    public String MainOrderID;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    OrdersService ordersService;


    public String TinyOrderSN(){
        String tinyOrderID = "";
        RReadWriteLock lock = redissonClient.getReadWriteLock("Lock_"+MainOrderID);
        RLock rlock = lock.writeLock();
        try {
            rlock.lock();
            ValueOperations<String, String> ops = redisTemplate.opsForValue();
            String orderSeq = ops.get("Seq_TinyOrderID"+MainOrderID);
            String serialNumber = "";
            if(orderSeq==null){
               Integer orderNo = getMainOrderIDFromDB(MainOrderID);
               ops.set("Seq_TinyOrderID"+MainOrderID,String.valueOf(orderNo+1));
                serialNumber = String.format("%02d", orderNo);
            }else{
                String serialSeq = ops.get("Seq_TinyOrderID"+MainOrderID);
                Integer serialNo = Integer.valueOf(serialSeq);
                serialNumber = String.format("%02d", serialNo);
                ops.set("Seq_TinyOrderID"+MainOrderID,String.valueOf(serialNo+1));
            }
            tinyOrderID = MainOrderID+"-"+serialNumber;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            rlock.unlock();
            return  tinyOrderID;
        }
    }

    public Integer  getMainOrderIDFromDB(String MainOrderID){
        Integer orderSerial= 1;
//        long a= System.currentTimeMillis();
        OrdersEntity order =  ordersService.getOne(new QueryWrapper<OrdersEntity>().
                 eq("MainOrderId",MainOrderID).isNull("MainOrderId").orderByAsc("CreateTime"));
//        System.out.println("查询耗时");
//        System.out.println(System.currentTimeMillis()-a+"毫秒");
        if(order!=null){
            String orderNO = order.getOrdersn();
            String[] arrayOrderNo = orderNO.split("-");
            orderSerial = Integer.valueOf(arrayOrderNo[1]);
        }
        return orderSerial;
    }

}
